from main.models import Friend,User
from main import db
from sqlalchemy.exc import InvalidRequestError
from main.utils import JSONHelper
from datetime import datetime
from sqlalchemy import or_, and_
from flask import render_template

def insert(friend):
    try:
        friend.time = datetime.now()
        db.session.add(friend)
        db.session.commit()
        return True
    except InvalidRequestError:
        db.session.rollback()
    except Exception as e:
        print(e)
        return False


# 传入用户名查询所有好友的名字
def query_friends_name(username):
    return db.session.query(Friend).filter(Friend.username == username).all()


def query_friends(id):
    return db.session.query(Friend, User).filter(Friend.user_id == id).join(User, Friend.friend_id == User.id).all()


if __name__ == '__main__':
    res = query_friends(1)
    print(res[0][0].to_json())
    print(res[0][1].to_json())